package com.jingantech.ngiam.util;

import com.alibaba.fastjson.JSONObject;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by fuzhong on 2017/1/10.
 */
public class XmlUtil {

    /**
     * 转换一个xml格式的字符串到json格式
     *
     * @param xml xml格式的字符串
     * @return 成功返回json 格式的字符串;失败反回null
     */
    public static  String xml2JsonString (String xml) {
        JSONObject obj = new JSONObject();
        try {
            InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
            SAXBuilder sb = new SAXBuilder();
            Document doc = sb.build(is);
            Element root = doc.getRootElement();
            obj.put(root.getName(), iterateElement(root));
            return obj.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 一个迭代方法
     *
     * @param element : org.jdom.Element
     * @return java.util.Map 实例
     */
    private static Map iterateElement(Element element) {
        List children = element.getChildren();
        Element et = null;
        Map map = new HashMap();
        List list = null;
        for (int i = 0; i < children.size(); i++) {
            list = new LinkedList();
            et = (Element) children.get(i);
            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0)
                    continue;
                if (map.containsKey(et.getName())) {
                    list = (List) map.get(et.getName());
                }
                list.add(iterateElement(et));
                if (list != null && list.size() == 1) {
                    map.put(et.getName(), list.get(0));
                } else {
                    map.put(et.getName(), list);
                }
            } else {
                if (map.containsKey(et.getName())) {
                    list = (List) map.get(et.getName());
                }
                list.add(et.getTextTrim());
                if (list != null && list.size() == 1) {
                    map.put(et.getName(), list.get(0));
                } else {
                    map.put(et.getName(), list);
                }
            }
        }
        return map;
    }

}
